package com.easipass.unifiedconfig.unic;

import java.util.HashSet;
import java.util.Set;

import com.easipass.unifiedconfig.MalformedUCIException;
import com.easipass.unifiedconfig.UCI;
import com.easipass.unifiedconfig.core.Authentication;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2010-1-22
 */
public final class UnicAuthentication extends Authentication {

	private String password;
	
	private AuthManager authManager;
	
	private Set<UCI> authUCIs = new HashSet<UCI>();
	
	public UnicAuthentication(AuthManager authManager, String domain, String user, String password) {
		super(domain, user);
		this.password = password;
		this.authManager = authManager;
	}
	
	public UnicAuthentication(String domain, String user, String password, UCI authUCI) {
		super(domain, user);
		this.password = password;
		if(authUCI != null)
			authUCIs.add(authUCI);
	}

	public static boolean matchPassword(UnicAuthentication a, String user, String password) {
		if(user == null) throw new NullPointerException("user");
		if(password == null) throw new NullPointerException("password");
		return user.equals(a.user) && password.equals(a.password);
	}
	
	public synchronized void refreshPrivillages() {
		if(authManager == null) return; // never refresh when authManager missing
		
		authUCIs.clear();
		for(String s : authManager.listModifyPrivillages(user))
			try {
				authUCIs.add(new UCI(s));
			} catch(MalformedUCIException e) {}
	}
	@Override
	public boolean authorized(UCI u) {
		for(UCI i : authUCIs)
			if(i.obtains(u))
				return true;
		return false;
	}
}
